/**
 * @Author: Your name
 * @Date:   2024-03-15 17:28:20
 * @Last Modified by:   Your name
 * @Last Modified time: 2024-03-15 18:33:57
 */
import React, { Component } from 'react';
import axios from 'axios';

class NotePad extends Component {
  state = {
    notes: [],
    inputValue: '',
    idCounter: 1,
  };

  handleInputChange = (e) => {
    this.setState({ inputValue: e.target.value });
  };

  handleAddNote = async () => {
    const { inputValue, notes, idCounter } = this.state;
    if (inputValue.trim() !== '') {
      // 先查询现有数据的数量
      const response = await axios.get('/api/noteCount');
      const count = response.data.length;

      // 根据现有数据的数量确定新日记的 ID
      const newId = count + 1;

      const currentDate = new Date().toLocaleDateString();
      const newNote = { id: newId, date: currentDate, content: inputValue };

      //   const currentDate = new Date().toLocaleDateString();
      //   const newNote = { id: idCounter, date: currentDate, content: inputValue };
      this.setState((prevState) => ({
        notes: [...prevState.notes, newNote],
        inputValue: newNote.content,
        idCounter: newNote.newId, // 递增计数器
      }));
      console.log(newId, newNote.content, currentDate);
      try {
        const response = await axios.post('/api/note', {
          id: newId, // 使用计数器作为 ID
          text: [newNote.content],
          date: currentDate,
        });

        if (response.data.message) {
          console.log(response.data.message);
        }
      } catch (err) {
        console.error(
          err.response?.data?.error ||
            'An error occurred while submitting the form.'
        );
      }
    }
  };

  render() {
    const { notes, inputValue } = this.state;

    return (
      <div className="container mx-auto mt-8">
        <h1 className="text-2xl font-bold mb-4">记事本</h1>
        <div className="flex">
          <textarea
            value={inputValue}
            onChange={this.handleInputChange}
            className="w-full h-48 p-2 border border-gray-300 rounded-lg focus:outline-none resize-none"
            placeholder="写点什么..."
          ></textarea>
        </div>
        <button
          onClick={this.handleAddNote}
          className="mt-4 bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 focus:outline-none"
        >
          添加日记
        </button>
        <div className="mt-8">
          {notes.map((note) => (
            <div key={note.id} className="mb-4">
              <p className="text-sm text-gray-500">{note.date}</p>
              <p className="mt-2">{note.content}</p>
            </div>
          ))}
        </div>
      </div>
    );
  }
}

export default NotePad;
